package com.funtl.screw.common.security.service;

import com.funtl.screw.admin.api.feign.RemoteUserService;
import com.funtl.screw.admin.vo.UserInfoVo;
import com.funtl.screw.common.core.constant.CacheConstants;
import com.funtl.screw.common.core.constant.SecurityConstants;
import com.funtl.screw.common.core.util.ResponseResult;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 用户信息
 *
 * @author Lusifer
 */
@Slf4j
@RequiredArgsConstructor
public class ServiceUserDetailsServiceImpl implements ServiceUserDetailsService {

    private final RemoteUserService remoteUserService;

    private final CacheManager cacheManager;

    /**
     * 用户密码登录
     *
     * @param username 用户名
     * @return UserDetails
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserByUsername(String username) {
        Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
        if (cache != null && cache.get(username) != null) {
            return cache.get(username, ServiceUser.class);
        }

        ResponseResult<UserInfoVo> result = remoteUserService.info(username, SecurityConstants.FROM_IN);
        UserDetails userDetails = getUserDetails(result);
        if (cache != null) {
            cache.put(username, userDetails);
        }
        return userDetails;
    }

    /**
     * 社交登录
     *
     * @param mobile mobile
     * @return UserDetails
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserBySocial(String mobile) {
        return getUserDetails(remoteUserService.getUserInfoByMobile(mobile, SecurityConstants.FROM_IN));
    }
}
